package com.itaming.lycheeframework.core.request;

import com.itaming.lycheeframework.support.utils.CharsetUtil;
import com.itaming.lycheeframework.support.utils.IoUtil;
import com.itaming.lycheeframework.support.utils.StringUtil;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.Getter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 防止 XSS 攻击的请求包装类
 *
 * @author A.Ming
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 原始请求
     */
    @Getter
    private final HttpServletRequest originalRequest;

    /**
     * 请求体缓存，避免只能读取一次
     */
    private byte[] cachedBody;

    /**
     * Parameter 缓存
     */
    private final Map<String, String> parameterCache = new ConcurrentHashMap<>();

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        originalRequest = request;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream(), CharsetUtil.getDefault()));
    }

    @Override
    public String getHeader(String name) {
        return StringUtil.htmlEscape(super.getHeader(name));
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        Enumeration<String> headers = super.getHeaders(name);
        return new Enumeration<>() {
            @Override
            public boolean hasMoreElements() {
                return headers.hasMoreElements();
            }

            @Override
            public String nextElement() {
                return StringUtil.htmlEscape(headers.nextElement());
            }
        };
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 只处理JSON
        String contentType = getHeader(HttpHeaders.CONTENT_TYPE);
        if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(contentType)) {
            return super.getInputStream();
        }

        // 缓存请求体
        if (cachedBody == null) {
            cachedBody = StringUtil.getBytes(StringUtil.htmlEscape(IoUtil.copyToString(super.getInputStream())).replace("&quot;", "\""));
        }

        // 返回缓存的请求体
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cachedBody);

        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    @Override
    public String getParameter(String name) {
        if (parameterCache.containsKey(name)) {
            return parameterCache.get(name);
        }

        String parameter = super.getParameter(name);

        if (StringUtil.isNotEmpty(parameter)) {
            parameter = StringUtil.htmlEscape(parameter);
            parameterCache.put(name, parameter);
        }
        return parameter;
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] parameterValues = super.getParameterValues(name);
        if (parameterValues != null) {
            for (int i = 0; i < parameterValues.length; i++) {
                parameterValues[i] = StringUtil.htmlEscape(parameterValues[i]);
            }
        }
        return parameterValues;
    }

}
